<?php

namespace plugin\webman\gateway;

use GatewayWorker\Lib\Gateway;

class Events
{
    public static function onWorkerStart($worker)
    {

    }

    public static function onConnect($client_id)
    {

    }

    public static function onWebSocketConnect($client_id, $data)
    {

    }

    public static function onMessage($client_id, $message)
    {
        // 客户端传递的是json数据
        $message_data = json_decode($message, true);
        if(!$message_data)
        {
            echo 'request data must json format';
            return ;
        }

        switch($message_data['msg_type'])
        {
            case 'ping':
                Gateway::sendToClient($client_id, json_encode(['msg_type'=>'ping success']));
                return;

            case 'login':

                //print_r($message_data);
                $city = base64_encode($message_data['city']);

                $_SESSION['user_id'] = $message_data['user_id'];
                $_SESSION['city']    = $city;
                //绑定用户
                Gateway::bindUid($client_id, $message_data['user_id']);
                //加入所在的城市分组
                Gateway::joinGroup($client_id, $city);

                $res['msg_type'] = 'login';
                $res['result']   = 'login_success';
                $res['to_user_id'] = $message_data['user_id'];

                Gateway::sendToClient($client_id, json_encode($res));
                return;

            case 'test':

                Gateway::sendToClient($client_id, json_encode($message_data));
                return;
        }
    }

    public static function onClose($client_id)
    {

    }

}
